<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { findAllUser, deleteUser, findUserByUsername, upUserStatus } from '../../api/user'
import dayjs from 'dayjs'

const tableData = ref<UserModel[]>([])
const getUserAll = async () => {
   const res = await findAllUser()
   tableData.value = res.data.map((item) => {
      return {
         ...item,
         createDate: dayjs(item.createDate).format('YYYY-MM-DD')
      }
   })
}

const deleteUsers = async (index: number, row: UserModel) => {
   await deleteUser(row.id)
   await getUserAll()
}

const username = ref('')
const findOneUser = async () => {
   const res = await findUserByUsername(username.value)
   tableData.value = res.data.map((item) => {
      return {
         ...item,
         createDate: dayjs(item.createDate).format('YYYY-MM-DD')
      }
   })
   username.value = ''
}

const upUserStatuses = async (index: number, row: UserModel) => {
   await upUserStatus(row.id)
   await getUserAll()
}

onMounted(() => {
   getUserAll()
})
</script>

<template>
   <div class="mt-4 p-5">
      <el-input v-model="username" style="max-width: 600px" placeholder="请输入用户名" class="input-with-select">
         <template #append>
            <el-button type="primary" @click="findOneUser" :icon="Search" />
         </template>
      </el-input>
      <el-button class="ml-4" @click="getUserAll">重置</el-button>
   </div>

   <div class="table p-5 w-full">
      <el-table :data="tableData" style="width: 100%">
         <el-table-column prop="createDate" label="创建日期" width="180" />
         <el-table-column prop="username" label="用户名" width="180" />
         <el-table-column prop="nickname" label="昵称" />
         <el-table-column prop="hobby" label="爱好" />
         <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
               <el-button link type="danger" size="small" @click="deleteUsers(scope.$index, scope.row)">删除</el-button>
               <el-button
                  @click="upUserStatuses(scope.$index, scope.row)"
                  link
                  :type="scope.row.status ? 'success' : 'warning'"
                  size="small"
                  >{{ scope.row.status ? '解封' : '禁言' }}</el-button
               >
            </template>
         </el-table-column>
      </el-table>
   </div>
</template>
